package cn.eastseven;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

/**
 * Hello world!
 * 
 */
public class App {

	static final Logger logger = Logger.getLogger(App.class);

	static final StringBuilder text = new StringBuilder("With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary. Logging equips the developer with detailed context for application failures. On the other hand, testing provides quality assurance and confidence in the application. Logging and testing should not be confused. They are complementary. When logging is wisely used, it can prove to be an essential tool. One of the distinctive features of log4j is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrarily fine granularity but also great ease. This helps to reduce the volume of logged output and the cost of logging. The target of the log output can be a file, an OutputStream, a java.io.Writer, a remote log4j server, a remote Unix Syslog daemon, or many other output targets.");
	
	static String username = "", password = "", host = "", from = "", to = "";
	
	public static void main(String[] args) {
		System.out.println("Hello World!");
		
		loadConfig();
		
		logger.info("Hello Log4J");
		logger.error(text.toString());
		
		Properties p = new Properties();
		p.put("mail.smtp.auth", "true");
		sendMail(p);
		
		Authenticator auth = getAuth(username, password);
		p.put("mail.smtp.host", host);
		sendMail(p, auth);
	}

	public static void loadConfig() {
		try {
			Configuration conf = new PropertiesConfiguration("log4j.properties");
			
			host     = conf.getString("log4j.appender.email.SMTPHost");
			username = conf.getString("log4j.appender.email.SMTPUsername");
			password = conf.getString("log4j.appender.email.SMTPPassword");
			from     = conf.getString("log4j.appender.email.From");
			to       = conf.getString("log4j.appender.email.To");
			
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public static void sendMail(Properties props) {
		
		Session session = Session.getDefaultInstance(props, null);
		MimeMessage msg = new MimeMessage(session);
		Transport transport = null;
		try {
			
			msg.setRecipients(RecipientType.TO, to);
			msg.setFrom(new InternetAddress(from));
			msg.setSubject("eastseven mail with java mail 1", "UTF-8");
			msg.setText("通过java mail 发送的邮件 1\n"+new Date(), "UTF-8");
			
			transport = session.getTransport("smtp");
			transport.connect(host, username, password);
			transport.sendMessage(msg, msg.getAllRecipients());
			logger.info(" 1 "+msg);
			
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			if(transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void sendMail(Properties props, Authenticator auth) {
		Session session = Session.getInstance(props, auth);
		MimeMessage msg = new MimeMessage(session);
		
		Multipart mp = new MimeMultipart();
		BodyPart bp = new MimeBodyPart();
		try {
			
			msg.setRecipients(RecipientType.TO, to);
			msg.setFrom(new InternetAddress(from));
			msg.setSubject("eastseven mail with java mail 2", "UTF-8");
			
			bp.setText("通过java mail 发送的邮件 2\n"+new Date());
			mp.addBodyPart(bp);
			msg.setContent(mp);
			msg.setSentDate(new Date());
			Transport.send(msg);
			logger.info(" 2 "+msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			
		}
	}
	
	public static Authenticator getAuth(final String smtpUsername, final String smtpPassword) {
		return new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(smtpUsername, smtpPassword);
			}
		};
	}
}
